#include "stdafx.h"
#include "GraphicsRepresentation.h"

namespace Cinetic
{

    GraphicsRepresentation::GraphicsRepresentation( std::shared_ptr<GraphicsComponent> g, Ogre::SceneManager* mgr ) :
        Representation(g),
        m_manager(mgr)
    {
        m_entity = m_manager->createEntity(g->mesh());
        m_scene_node = m_manager->createSceneNode();
        m_scene_node->attachObject(m_entity);
        m_manager->getRootSceneNode()->addChild(m_scene_node);
        m_mesh_changed_callback.Bind<GraphicsRepresentation, &GraphicsRepresentation::on_mesh_changed>(this);
        g->MeshChanged += m_mesh_changed_callback;
    }

    GraphicsRepresentation::~GraphicsRepresentation()
    {
        auto g = std::static_pointer_cast<GraphicsComponent>(model().lock());
        if (g) {
            g->MeshChanged -= m_mesh_changed_callback;
        }
    }

    void GraphicsRepresentation::on_mesh_changed( const Ogre::String& mesh )
    {
        m_scene_node->detachObject(m_entity);
        m_manager->destroyEntity(m_entity);
        m_entity = m_manager->createEntity(std::static_pointer_cast<GraphicsComponent>(model().lock())->mesh());
        m_scene_node->attachObject(m_entity);
    }

}